package svc

import (
	"shorturl/internal/config"
	"shorturl/model"
	"shorturl/sequence"

	"github.com/bits-and-blooms/bloom/v3"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
)

type ServiceContext struct {
	Config               config.Config
	ShortUrlMapModel     model.ShortUrlMapModel
	Seq                  sequence.Sequence
	ShortUrlBlackListMap map[string]struct{}
	Filter               *bloom.BloomFilter
}

func NewServiceContext(c config.Config) *ServiceContext {
	conn := sqlx.NewMysql(c.ShortUrlDB.DSN)
	// 将黑名单list 转为map
	ShortUrlBlackListMap := make(map[string]struct{}, len(c.ShortUrlBlackList))
	for _, u := range c.ShortUrlBlackList {
		ShortUrlBlackListMap[u] = struct{}{}
	}

	// bloomfilter 初始化
	filter := bloom.NewWithEstimates(1000000, 0.01)
	return &ServiceContext{
		Config:               c,
		ShortUrlMapModel:     model.NewShortUrlMapModel(conn, c.CacheRedis),
		Seq:                  sequence.NewMysql(c.ShortUrlDB.DSN),
		ShortUrlBlackListMap: ShortUrlBlackListMap,
		Filter:          filter,
	}
}
